package util;

import java.util.Arrays;

public class ArraysUtil {
    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 3, 3, 1, 2};

        System.out.println(Arrays.toString(getIndexByTarget(arr, 1)));

        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(delDoubleElement3(arr)));
    }

    public static int getMaxElement(int[] arr) {
        if (arr == null || arr.length == 0)
            return -1;
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                arr[i] = arr[i] ^ max;
                max = arr[i] ^ max;
                arr[i] = arr[i] ^ max;
            }
        }
        return max;
    }

    public static int[] getIndexByTarget(int[] arr, int target) {
        if (arr == null || arr.length == 0)
            return new int[]{-1};
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                count++;
            }
        }
        if (count == 0) {
            return new int[]{-1};
        }

        int[] temp = new int[count];
        int pos = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                temp[pos++] = i;
            }
        }
        return temp;
    }

    public static int[] delByIndex(int[] arr, int index) {
        if (null == arr || arr.length == 0 || index < 0 || index > arr.length - 1)
            return arr;

        int[] temp = new int[arr.length - 1];

        int pos = 0;
        for (int i = 0; i < arr.length; i++) {
            if (i != index) {
                temp[pos++] = arr[i];
            }
        }
        return temp;
    }

    public static int[] delByElement(int[] arr, int target) {
        int count = 0;
        ;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target)
                count++;
        }

        int[] temp = new int[arr.length - count];

        int pos = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != target) {
                temp[pos++] = arr[i];
            }
        }
        return temp;
    }

    public static int[] delDoubleElement3(int[] arr) {
        if (null == arr || arr.length == 0)
            return arr;
        int pos = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {

                if (arr[i] == arr[j]) {
                    arr = delByIndex(arr,j);
                    j--;
                }
            }
        }
        return arr;
    }
}